const Koa = require('koa');
const app = new Koa();
const views = require('koa-views');
const json = require('koa-json');
const onerror = require('koa-onerror');
const koaBody = require('koa-body');
const bodyparser = require('koa-bodyparser');
const logger = require('koa-logger');
const cors = require('koa2-cors');
const coreWhiteHandler=require('./middleware/coreWhiteListHandler');
const index = require('./routes');
let errorHandler = require('./middleware/errorHandler');
let urlFilter = require('./middleware/urlFilter');
const config = require('./config');
const {accessLogger, infoLogger, errorLogger, con} = config.logger;
// error handler
onerror(app);
//配置进入日志
app.use(accessLogger());
// middlewares

app.use(bodyparser({
    enableTypes: ['json', 'form', 'text']
}));
app.use(json());
app.use(logger());
app.use(require('koa-static')(__dirname + '/public'));

app.use(views(__dirname + '/views', {
    extension: 'pug'
}));
//跨域
//console.log(config.core);
app.use(cors(config.core));
//app.use(cors());
// logger
app.use(async (ctx, next) => {
    const start = new Date();
    //systemLogger.debug('第一个中间件开始');
    con.info('第一个中间件开始');
    // /console.log('第一个中间件开始');
    await next();
    const ms = new Date() - start;
    con.info('第一个中间件结束');
    infoLogger.info(`${ctx.method} ${ctx.url} - ${ms}ms`);
});
//域名白名单
//app.use(coreWhiteHandler());
//地址过滤
app.use(urlFilter());
//异常处理中间件
app.use(errorHandler());
// routes
app.use(index.routes(), index.allowedMethods());
//app.use(users.routes(), users.allowedMethods());
//app.use(book.routes(),book.allowedMethods());
// error-handling

app.on('error', (err, ctx) => {
    console.error('server error', err, ctx);
    //logger.error(">>>>>错误",err);
});
module.exports = app;
